import React from 'react';
import { Breadcrumb } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import { routes, MyRouteObject } from '@/router/index';
import styles from './styles.module.css';

const BreadcrumbNav: React.FC = () => {
  const location = useLocation();

  // 从路由配置中查找路由信息
  const findRouteConfig = (path: string, currentRoutes: MyRouteObject[] = routes): MyRouteObject | null => {
    // 将传入的路径规范化，移除尾部斜杠
    const normalizedPath = path.endsWith('/') ? path.slice(0, -1) : path;
    const pathSegments = normalizedPath.split('/').filter(Boolean);
    
    // 如果是空路径，直接返回null
    if (pathSegments.length === 0) return null;
    
    // 查找特定的路径模式，处理嵌套路由
    if (pathSegments.length > 1) {
      // 分析路径段，构建可能的路由路径
      const parentSegment = pathSegments[0];
      
      // 先查找一级路由
      for (const route of currentRoutes) {
        // 检查是否是匹配的一级路由
        if (route.path === `/${parentSegment}` || route.path === parentSegment) {
          // 如果是最终路径，直接返回
          if (pathSegments.length === 1) {
            return route;
          }
          
          // 如果有子路由，并且当前不是最终路径，递归查找
          if (route.children && route.children.length > 0) {
            // 构建剩余路径
            const remainingPath = '/' + pathSegments.slice(1).join('/');
            
            // 遍历子路由
            for (const childRoute of route.children) {
              // 需要处理多种子路由格式
              const childPath = childRoute.path;
              
              // 如果子路由路径与剩余路径匹配
              if (childPath === remainingPath || `/${childPath}` === remainingPath) {
                return childRoute;
              }
              
              // 处理多级嵌套的情况，例如/admin/contest/list中的contest/list部分
              const lastSegment = pathSegments[pathSegments.length - 1];
              if (childPath === lastSegment) {
                return childRoute;
              }
              
              // 处理完整路径匹配，例如contest/list
              const fullChildPath = `${parentSegment}/${childPath}`;
              if (normalizedPath === `/${fullChildPath}`) {
                return childRoute;
              }
              
              // 处理带有children的子路由
              if (childRoute.children && childRoute.children.length > 0) {
                // 例如contest下面的list
                const childSegment = pathSegments[1];
                if (childPath === childSegment) {
                  // 检查路径最后一段是否匹配
                  const lastSegment = pathSegments[pathSegments.length - 1];
                  for (const grandChildRoute of childRoute.children) {
                    if (grandChildRoute.path === lastSegment || grandChildRoute.path === 'list') {
                      return grandChildRoute;
                    }
                  }
                  // 如果没有找到匹配的子路由，则返回父级路由
                  return childRoute;
                }
              }
            }
          }
        }
      }
    }
    
    // 常规匹配逻辑
    for (const route of currentRoutes) {
      // 检查完整路径
      if (route.path === normalizedPath || `/${route.path}` === normalizedPath) {
        return route;
      }

      // 检查参数化路由 (如 :id)
      if (route.path && typeof route.path === 'string' && route.path.includes(':')) {
        const routeParts = route.path.split('/').filter(Boolean);
        const pathParts = normalizedPath.split('/').filter(Boolean);
        
        if (routeParts.length === pathParts.length) {
          let isMatch = true;
          for (let i = 0; i < routeParts.length; i++) {
            if (!routeParts[i].startsWith(':') && routeParts[i] !== pathParts[i]) {
              isMatch = false;
              break;
            }
          }
          if (isMatch) return route;
        }
      }

      // 递归检查子路由
      if (route.children && route.children.length) {
        const foundRoute = findRouteConfig(normalizedPath, route.children);
        if (foundRoute) return foundRoute;
      }
    }
    
    // 针对特定路径的硬编码匹配，确保能找到关键路由
    if (normalizedPath === '/admin/contest') {
      return { breadcrumb: '比赛管理' } as MyRouteObject;
    }
    if (normalizedPath === '/admin/contest/list') {
      return { breadcrumb: '比赛列表' } as MyRouteObject;
    }
    if (normalizedPath === '/admin/problem') {
      return { breadcrumb: '题目管理' } as MyRouteObject;
    }
    
    return null;
  };

  const generateBreadcrumbItems = () => {
    const breadcrumbItems = [];
    
    // 添加首页
    breadcrumbItems.push({
      key: '/',
      title: <Link to="/">首页</Link>,
    });

    // 分割路径
    const pathSegments = location.pathname.split('/').filter(Boolean);
    let currentPath = '';

    // 避免重复的breadcrumb
    const addedBreadcrumbs = new Set(['首页']);

    // 逐段处理路径
    for (let i = 0; i < pathSegments.length; i++) {
      const segment = pathSegments[i];
      currentPath += `/${segment}`;
      
      // 获取当前路径的路由配置
      const routeConfig = findRouteConfig(currentPath);
      //console.log(currentPath, routeConfig);
      
      // 如果找到路由配置且有breadcrumb，则显示breadcrumb
      if (routeConfig && routeConfig.breadcrumb) {
        // 检查是否已添加过此breadcrumb
        if (!addedBreadcrumbs.has(routeConfig.breadcrumb)) {
          breadcrumbItems.push({
            key: currentPath,
            title: <Link to={currentPath}>{routeConfig.breadcrumb}</Link>,
          });
          addedBreadcrumbs.add(routeConfig.breadcrumb);
        }
      } 
      // 否则显示路径段名（但跳过admin和client路径段）
      else if (segment !== 'admin' && segment !== 'client') {
        breadcrumbItems.push({
          key: currentPath,
          title: <Link to={currentPath}>{segment}</Link>,
        });
      }
    }
    
    return breadcrumbItems;
  };

  return (
    <Breadcrumb className={styles.breadcrumb} items={generateBreadcrumbItems()} />
  );
};

export default BreadcrumbNav; 